﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;
using Microsoft.Windows.Controls;
using System.Windows;

namespace SYcwpb.Helpers
{    

    /// <summary>
    /// Validates data which is bound from a DataSet
    /// </summary>
    public class DataRowValidation : ValidationRule
    {      
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            // if this rule is being applied to a cell we will be inspecting a binding expression
            if (value is BindingExpression)
            {
                // obtain the row which is being validated
                BindingExpression expression = value as BindingExpression;
                DataRow row = ((DataRowView)expression.DataItem).Row;

                // determine the column to validate
                string propertyName = expression.ParentBinding.Path.Path;

                return ValidateColumn(propertyName, row);
            }

            // if this rule is being applied to a cell we will be inspecting a binding group
            else if (value is BindingGroup)
            {
                BindingGroup group = (BindingGroup)value;

                // iterate over all the bound items (this should always be one!)
                foreach (var item in group.Items)
                {
                    DataRow row = ((DataRowView)item).Row;

                    // validate against the metadata for each column
                    foreach (DataColumn column in row.Table.Columns)
                    {
                        ValidationResult result = ValidateColumn(column.ColumnName, row);
                        if (result != ValidationResult.ValidResult)
                        {
                            return result;
                        }
                    }                   
                }
            }

            return ValidationResult.ValidResult;
        }

        /// <summary>
        /// Validates a DataRow value associated with the given named column
        /// </summary>
        private ValidationResult ValidateColumn(string columnName, DataRow row)
        {
            DataTable table = row.Table;
            DataColumn column = table.Columns[columnName];
            object cellValue;
            try
            {
                cellValue = row[column.ColumnName];
            }
            catch (RowNotInTableException)
            {
                return ValidationResult.ValidResult;
            }

            // check for null values
            if (cellValue == null || cellValue.Equals(string.Empty) || cellValue.Equals(System.DBNull.Value))
            {
                if (!column.AllowDBNull)
                {
                    return new ValidationResult(false, "值不能为空");
                }
                else
                {
                    return ValidationResult.ValidResult;
                }
            }

            if (column.DataType == typeof(double))
            {
                string strVal = Convert.ToString(cellValue) ;

                if (!Regex.IsMatch(strVal, @"^(\d+\.)?\d+$"))
                {
                    return new ValidationResult(false, " 请输入有效的正实数！ ");
                }

                if (strVal != null && (Convert.ToDouble(cellValue) < 0 || Convert.ToDouble(cellValue) > 10000))
                {
                    return new ValidationResult(false, " 数值 过大！请确认！ ");
                }

                //if(strVal != null && strVal.Substring(strVal.IndexOf('.') + 1).Length > 2)
                //{
                //    return new ValidationResult(false, " 请精确到小数点后两位！ ");
                //}
            }

            // check for unique constraints
            //if (column.Unique)
            //{
            //    // iterate over all the rows in the table comparing the value for this column
            //    foreach (DataRow compareRow in row.Table.Rows)
            //    {
            //        if (compareRow!=row && cellValue.Equals(compareRow[column]))
            //        {
            //            return new ValidationResult(false, column.ColumnName + " must be unique");
            //        }
            //    }
            //}

            return ValidationResult.ValidResult;
        }

        /// <summary>
        /// 获取DataGrid的第一个被发现的验证错误结果。
        /// </summary>
        /// <param name="dg">被检查的DataGrid实例。</param>
        /// <returns>错误结果。</returns>
        public static ValidationError GetDataGridRowsFirstError(DataGrid dg)
        {
            ValidationError err = null;
            for (int i = 0; i < dg.Items.Count; i++)
            {
                DependencyObject o = dg.ItemContainerGenerator.ContainerFromIndex(i);
                if (o != null)
                {
                    bool hasError = Validation.GetHasError(o);
                    if (hasError)
                    {
                        err = Validation.GetErrors(o)[0];
                        break;
                    }
                }
                
            }
            return err;
        }

        /// <summary>
        /// 执行检查DataGrid，并提示第一个错误。重新定位到错误单元格。
        /// </summary>
        /// <param name="dg">被检查的DataGrid实例。</param>
        /// <returns>true 有错并定位，false 无错、返回</returns>
        public static bool ExcutedCheckedDataGridValidation(DataGrid dg)
        {
            ValidationError err = GetDataGridRowsFirstError(dg);
            if (err != null)
            {
                string errColName = ((System.Windows.Data.BindingExpression)err.BindingInError).ParentBinding.Path.Path;
                DataGridColumn errCol = dg.Columns.Single(p =>
                {
                    if (((Binding)((DataGridTextColumn)p).Binding).Path.Path == errColName)
                        return true;
                    else return false;
                });
                //string errRow = ((DataRowView)((System.Windows.Data.BindingExpression)err.BindingInError).DataItem)["SWH"].ToString();
                //dg.Items.IndexOf(((System.Windows.Data.BindingExpression)err.BindingInError).DataItem);
                dg.SelectedItem = ((System.Windows.Data.BindingExpression)err.BindingInError).DataItem;
                int errRowIndex = dg.SelectedIndex;
                //MessageBox.Show(string.Format("第\"{0}\"行 的\"{1}\"列的单元格数据不合法(以红色标出)，请填写正确后再执行其他操作。", errRowIndex + 1, errCol.Header), "系统消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                //MessageBoxHelper.ShowError(string.Format("第\"{0}\"行 的\"{1}\"列的单元格数据不合法(以红色标出)，请填写正确后再执行其他操作。", errRowIndex + 1, errCol.Header));
                MessageBoxHelper.ShowError(string.Format("\"{0}\"列的单元格数据不合法(以红色标出)，请填写正确后再执行其他操作。", errCol.Header));

                dg.CurrentCell = new DataGridCellInfo(dg.SelectedItem, errCol);
                if (!((DataRowView)dg.CurrentItem).IsEdit)
                {
                    ((DataRowView)dg.CurrentItem).BeginEdit();

                }
                TextBox txt = dg.CurrentColumn.GetCellContent(dg.CurrentItem) as TextBox;
                if (null != txt)
                    txt.Focus();
                return true;
            }
            else
            {
                return false;
            }
        }
    }

   
   
}
